package com.qingyun.web.security.handle;

import cn.hutool.core.lang.Validator;
import com.alibaba.fastjson.JSON;

import com.qingyun.common.constant.Constants;
import com.qingyun.common.core.domain.AjaxResult;
import com.qingyun.common.core.domain.model.LoginUser;
import com.qingyun.common.utils.ServletUtils;
import com.qingyun.framework.web.service.AsyncService;
import com.qingyun.framework.web.service.TokenService;
import com.qingyun.security.model.shop.AppLoginUser;
import com.qingyun.security.model.tenant.TenantLoginUser;
import com.qingyun.security.model.tiktok.TikTokLoginUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义退出处理类 返回成功
 *
 * @author dangyonghang
 */
@Component
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler
{
    @Autowired
    private TokenService tokenService;

    @Autowired
	private AsyncService asyncService;

    /**
     * 退出处理
     *
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
		AppLoginUser appUser = tokenService.getAppUser(request);
		String userName=null;
        if (Validator.isNotNull(loginUser))
        {
             userName = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
        }
        else if(Validator.isNotNull(appUser)){
			  userName = appUser.getUsername();
			  tokenService.delAppUser(appUser.getToken());
		}
        // 记录用户退出日志
        if(StringUtils.isNotBlank(userName)){
			asyncService.recordLogininfor(userName, Constants.LOGOUT,"退出成功",request);
        }

        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(HttpStatus.OK.value(),"退出成功")));
    }
}
